﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using seejee_Backendium.Core.Interfaces;
using seejee_Backendium.Core.Models;
using seejee_Backendium.Data.DbContest;
using seejee_Backendium.Data.Services;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using static QRCoder.PayloadGenerator.SwissQrCode;

namespace seejee_Backendium.WEB.Controllers
{
    [ApiController]
    [Route("api/")]
    [Authorize]
    public class UserController : ControllerBase
    {
        private readonly IUserService _userService;
        private readonly ApplicationDbContext _context;
        private readonly IConfiguration _configuration; // 新增字段
        private readonly ILogger<UserController> _logger;

        public UserController(IUserService userService, IConfiguration configuration, ILogger<UserController> logger, ApplicationDbContext context)
        {
            _userService = userService;
            _configuration = configuration;
            _logger = logger; // 
            _context = context; // 注入 ApplicationDbContext
        }
        // 登录接口
        [AllowAnonymous] // 登录接口允许匿名访问
        [HttpPost("login")]
        public IActionResult Login([FromBody] LoginRequest request)
        {
            if (_userService.ValidateUser(request.cCusName, request.cCusPassword))
            {
                // 生成 JWT Token
                var claims = new[]
                {
            new Claim(ClaimTypes.Name, request.cCusName)
        };
                var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:Key"] ?? "your-very-strong-key"));
                var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

                var token = new JwtSecurityToken(
                    issuer: _configuration["Jwt:Issuer"] ?? "your-app",
                    audience: null,
                    claims: claims,
                    expires: DateTime.Now.AddHours(2), // token有效期为2小时
                    signingCredentials: creds);

                var tokenString = new JwtSecurityTokenHandler().WriteToken(token);

                //return Ok(new { Message = "登录成功" });
                return Ok(new
                {
                    success = true,
                    token = tokenString,
                });
            }
            else
            {
                //return Unauthorized(new { Message = "用户名或密码错误" });
                return Ok(new { success = false });
            }
        }
        // 获取用户列表
        [HttpGet("user/list")]
        public IActionResult GetUser([FromQuery] int pageIndex, [FromQuery] int pageSize, [FromQuery] string keyword = "")
        {
            if (pageIndex < 1 || pageSize < 1)
            {
                return BadRequest(new { success = false, message = "参数错误" });
            }
            try
            {
                var users = _userService.GetAllUsers(pageIndex, pageSize, keyword);
                return Ok(new { success = true, data = users });
            }
            catch (Exception ex)
            {
                // 可选：记录日志
                return StatusCode(500, new { success = false, message = ex.Message });
            }

        }

        // 获取用户详情
        [HttpGet("user/list/{cCusName}")]
        public IActionResult GetUserById(string cCusName)
        {
            var user = _userService.GetUserById(cCusName);
            if (user == null)
                return NotFound(new { Success = false, Message = "用户不存在" });
            return Ok(user);
        }
        //添加用户
        [HttpPost("user/insert")]
        public async Task<IActionResult> InsertUser([FromBody] UserInsertDTO user)
        {
            //  生成随机盐值 
            //var salt = PasswordService.GenerateSalt();
            //Console.WriteLine(salt);
            //生成固定盐值
            //var salt = PasswordService.GenerateSalt();

            //  二次哈希处理 
            //var finalHash = PasswordService.HashPassword(user.cCusPassword, salt);

            //  创建用户实体
            var users = new UserInsertDTO
            {
                cCusName = user.cCusName,
                //cCusRealName = user.cCusRealName,
                //cCusPassword = finalHash,
                iCusPermissions = user.iCusPermissions,
                cCusUserKey = user.cCusUserKey,
                cCusLicenses = user.cCusLicenses,
                dCusExpiryDate = user.dCusExpiryDate,
                // 使用生成的盐值
                //Salt = salt,
                //dCusCreateTime = DateTime.UtcNow
                dCusCreateTime = user.dCusCreateTime
            };
            var result = _userService.InsertUser(users);
            if (result)
                return Ok(new { Success = true, Message = "用户添加成功" });
            return StatusCode(500, new { Success = false, Message = "用户添加失败" });
        }

        //查询用户名是否重复
        [HttpGet("user/list/name")]
        public bool UserNameSearch(string cCusName)
        {

            var result = _userService.UserNameSearch(cCusName);
            if (result)
                return false;
            return true;

        }
    
        // 用户名唯一性校验接口
        [HttpGet("user/check-username")]
        public async Task<IActionResult> CheckUsernameUnique([FromQuery] string cCusName)
        {
            //// 基础校验 
            //if (string.IsNullOrWhiteSpace(username))
            //    return BadRequest(new { error = "用户名不能为空" });

            //if (username.Length < 3 || username.Length > 20)
            //    return BadRequest(new { error = "用户名长度需在3-20字符之间" });

            // 数据库查询 [[1]][[6]]
            try
            {
                //bool exists = await _context.UserNameDTOs
                //    .AnyAsync(u => u.cCusName == cCusName);
                bool exists = await _context.UserNameDTOs.AnyAsync(u => u.cCusName == cCusName);
                return Ok(new { exists });
            }
            catch (Exception ex)
            {
                // 记录日志
                _logger.LogError(ex, "用户名校验失败");
                return StatusCode(500, new { error = "服务器内部错误" });
            }
        }
        //修改密码
        [HttpPut("user/setpassword")]
        public IActionResult UpdatePassword([FromBody] UserPasswordDTO userUpdatePassword)
        {
            try
            {
                var result = _userService.UpdatePassword(userUpdatePassword);
                if (result)
                    return Ok(new { Success = true, Message = "密码修改成功" });
                return StatusCode(500, new { Success = false, Message = "密码修改失败" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "密码修改失败");
                return StatusCode(500, new { Success = false, Message = "服务器错误" });
            }
        }

        //修改用户信息
        [HttpPut("user/update")]
        public IActionResult UpdateUser([FromBody] UserUpdate user)
        {
            try
            {
                var result = _userService.UpdateUser(user);
                if (result)
                    return Ok(new { Success = true, Message = "用户信息更新成功" });
                return StatusCode(500, new { Success = false, Message = "用户信息更新失败" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "用户信息更新失败");
                return StatusCode(500, new { Success = false, Message = "服务器错误" });
            }
        }
        // 删除用户
        [HttpDelete("user/delete/{cCusName}")]
        public IActionResult DeleteUser(string cCusName)
        {
            try
            {
                var result = _userService.DeleteUser(cCusName);
                if (result)
                    return Ok(new { Success = true, Message = "用户删除成功" });
                return StatusCode(500, new { Success = false, Message = "用户删除失败" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "用户删除失败");
                return StatusCode(500, new { Success = false, Message = "服务器错误" });
            }
        }

        public class LoginRequest
        {
            public string cCusName { get; set; }
            public string cCusPassword { get; set; }
        }
        public class UserInfo
        {
            public int iCusID { get; set; }
            public string cCusName { get; set; }
            public string cCusPassword { get; set; }
            //public string cCusRealName { get; set; }
            public string cCusUserKey { get; set; }
            public string cCusLicenses { get; set; }

            public DateTime dCusExpiryDate { get; set; }
        }
        public class UserNameSearchDTO
        {
            public string cCusName { get; set; }
        }
    }
}
